<template>
	<el-dialog :visible.sync="visible" width="580px">
		<el-form label-width="80px" style="max-height: 80vh; overflow: auto">
			<el-form-item label="权限管理">
				<el-tree
					:data="tree"
					show-checkbox
					node-key="id"
					:default-expanded-keys="[2, 3]"
					:default-checked-keys="[5]"
					:props="defaultProps"
					ref="ElTree"
					default-expand-all
				></el-tree>
			</el-form-item>
		</el-form>

		<template #footer>
			<el-button @click="visible = false">取 消</el-button>
			<el-button type="primary" @click="submit">确 定</el-button>
		</template>
	</el-dialog>
</template>

<script>
import request from "@/common/request"

export default {
	name: "edit",
	props: {},
	data() {
		return {
			visible: false,
			tree: [],
			defaultProps: {
				children: "children",
				label: "name",
			},
			id: "",
		}
	},
	computed: {},
	methods: {
		init(id) {
			this.id = id
			this.visible = true
			this.getInfo()
		},
		async getInfo() {
			try {
				const {
					code,
					data: { allData, checkedData },
					msg,
				} = await request("get", "/cms/cmsChannel/authInfo", {
					roleId: this.id,
				})
				if (code != 0) {
					throw new Error(msg)
				}
				this.tree = allData

				const ids = checkedData.map(item => item.id)
				this.setTreeCheck(ids)
			} catch (error) {
				this.$message.error(error)
			}
		},
		async submit() {
			this.visible = false

			try {
				const { code, msg } = await request("post", "/cms/cmsRoleChannel/save", {
					roleId: this.id,
					channelIds: this.$refs.ElTree.getCheckedKeys(),
				})
				if (code != 0) {
					throw new Error(msg)
				}
				this.$message.success("保存成功")
				this.visible = false
				this.id = ""
			} catch (error) {
				this.$message.error(error)
			}
		},
		setTreeCheck(checkList) {
			this.$nextTick(() => {
				this.$refs.ElTree.setCheckedKeys(checkList)
			})
		},
	},
	components: {},
}
</script>

<style lang="scss" scoped>
.edit {
}
</style>
